/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.unice.miage.oobdoo.servlet;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.RequestContext;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photosets.Photoset;
import com.aetrion.flickr.photosets.PhotosetsInterface;
import com.google.gdata.client.Query;
import com.google.gdata.util.ServiceException;
import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.types.Album;
import com.unice.miage.oobdoo.entity.Utilisateur;
import com.unice.miage.oobdoo.enumeration.Statut;
import com.unice.miage.oobdoo.manager.AlbumManager;
import com.unice.miage.oobdoo.manager.PhotoManager;
import com.unice.miage.oobdoo.manager.UtilisateurManager;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javaxt.io.Image;

import java.io.File;
import java.net.URL;

import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.data.photos.AlbumFeed;
import com.google.gdata.data.photos.PhotoEntry;
import com.google.gdata.data.photos.UserFeed;
import java.util.Iterator;

/**
 *
 * @author Jeremy Romano
 */
public class ImportServlet extends HttpServlet {

    @EJB
    private UtilisateurManager utilisateurManager;
    @EJB
    private AlbumManager albumManager;
    @EJB
    private PhotoManager photoManager;
    String FACEBOOK_API_ID = "175962519155144";
    String FACEBOOK_API_SECRET = "320d63da1c62daae63cf457bb557f936";
    String FLICKR_API_KEY = "b530efd6e5a9f25353f2e85c7d452e02";
    String FLICKR_API_SECRET = "0fbc40addb1a6f53";

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String source = request.getParameter("source");
        String forwardTo = "import/index.jsp";

        HttpSession session = request.getSession(true);
        int id = Integer.valueOf(session.getAttribute("id").toString());

        Utilisateur u = utilisateurManager.getUtilisateurById(id);

        boolean tokenFBExist = (u.getAccess_token_fb() != null);
        boolean tokenPExist = (u.getAccess_token_picasa() != null);
        boolean tokenFExist = (u.getAccess_token_flickr() != null);

        if (tokenFBExist) {
            request.setAttribute("facebook", 1);
        }

        if (tokenPExist) {
            request.setAttribute("picasa", 1);
        }

        if (tokenFExist) {
            request.setAttribute("flickr", 1);
        }

        if (source != null) {
            forwardTo = "";
            if (source.equals("facebook")) {
                String action = request.getParameter("action");
                if (action != null && action.equals("import")) {
                    String submit = request.getParameter("submit");
                    if (submit != null) {
                        String statut = request.getParameter("statut");
                        Statut s = Statut.valueOf(statut);
                        String access_token_fb = u.getAccess_token_fb();

                        FacebookClient facebookClient = new DefaultFacebookClient(access_token_fb);
                        com.restfb.types.Album aFB = facebookClient.fetchObject(request.getParameter("album"), com.restfb.types.Album.class);

                        // TODO Creation de l'album 
                        com.unice.miage.oobdoo.entity.Album newAlbum = albumManager.creerAlbum(u, aFB.getName(), aFB.getDescription(), s);
                        utilisateurManager.addAlbum(u, newAlbum);

                        // TODO2 Recupération des photos pour les ajouter
                        com.restfb.types.Photo cover = facebookClient.fetchObject(aFB.getCoverPhoto(), com.restfb.types.Photo.class);

                        Connection<com.restfb.types.Photo> photos = facebookClient.fetchConnection(aFB.getId() + "/photos", com.restfb.types.Photo.class);

                        for (com.restfb.types.Photo p : photos.getData()) {
                            BufferedImage image = null;
                            try {

                                URL url = new URL(p.getSource());
                                uploadPhotoByUrl(u, newAlbum, url, p.getId());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                        forwardTo = "/AlbumServlet?action=list";
                        RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                        dp.forward(request, response);

                    } else {
                        System.out.println("No submit from form FB import");
                        forwardTo = "import/index.jsp";
                    }
                } else {
                    String access_token_fb = u.getAccess_token_fb();

                    if (access_token_fb != null) {
                        // on a deja l'access_token 
                        HashMap<String, String> lstAlbums = getListOfFBAlbums(access_token_fb);

                        request.setAttribute("lstAlbums", lstAlbums);
                        forwardTo = "import/facebook.jsp";
                        RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                        dp.forward(request, response);
                    }
                }

            } else if (source.equals("picasa")) {
                // On recupere l'action
                String action = request.getParameter("action");

                // Si on a un import
                if (action != null && action.equals("import")) {
                    String submit = request.getParameter("submit");
                    if (submit != null) {
                        try {
                            String statut = request.getParameter("statut");
                            Statut s = Statut.valueOf(statut);
                            String access_token_picasa = u.getAccess_token_picasa();

                            PicasawebService ps = new PicasawebService("oobdoo");
                            ps.setAuthSubToken(access_token_picasa, null);

                            URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/default/albumid/" + request.getParameter("album"));

                            AlbumFeed myAlbumFeed = ps.getFeed(feedUrl, AlbumFeed.class);

                            // TODO Creation de l'album 
                            com.unice.miage.oobdoo.entity.Album newAlbum = albumManager.creerAlbum(u, myAlbumFeed.getTitle().getPlainText(), myAlbumFeed.getDescription().getPlainText(), s);
                            utilisateurManager.addAlbum(u, newAlbum);

                            // TODO2 Recupération des photos pour les ajouter
                            for (PhotoEntry p : myAlbumFeed.getPhotoEntries()) {
                                BufferedImage image = null;
                                try {
                                    URL url = new URL(p.getMediaContents().get(0).getUrl());
                                    uploadPhotoByUrl(u, newAlbum, url, p.getTitle().getPlainText().split("[.]")[0]);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            forwardTo = "/AlbumServlet?action=list";
                            RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                            dp.forward(request, response);
                        } catch (ServiceException ex) {
                            Logger.getLogger(ImportServlet.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else {
                        System.out.println("No submit from form PICASA import");
                        forwardTo = "import/index.jsp";
                    }
                    // Sinon on tombe dans le choix de l'album
                } else {
                    // On recupere l'access token picasa de l'utilisateur
                    String access_token_picasa = u.getAccess_token_picasa();

                    // Si il en a un
                    if (access_token_picasa != null) {
                        HashMap<String, String> lstAlbums = getListOfPICASAAlbums(access_token_picasa);

                        request.setAttribute("lstAlbums", lstAlbums);
                        forwardTo = "import/picasa.jsp";
                        RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                        dp.forward(request, response);
                    }
                }
                // Inspire de http://blog.theunical.com/java/flickr-example-to-upload-photos-using-java/
            } else if (source.equals("flickr")) {
                // On recupere l'action
                String action = request.getParameter("action");

                // Si on a un import
                if (action != null && action.equals("import")) {
                    String submit = request.getParameter("submit");
                    if (submit != null) {
                        try {
                            String statut = request.getParameter("statut");
                            Statut s = Statut.valueOf(statut);
                            String access_token_flickr = u.getAccess_token_flickr();

                            Auth auth;
                            RequestContext requestContext;	// Used for making signed calls to Flickr

                            Flickr flickr = new Flickr(FLICKR_API_KEY, FLICKR_API_SECRET, new REST());

                            requestContext = RequestContext.getRequestContext();
                            requestContext.setSharedSecret(FLICKR_API_SECRET);

                            AuthInterface authInterface = flickr.getAuthInterface();
                            auth = authInterface.checkToken(access_token_flickr);

                            requestContext.setAuth(auth);

                            PhotosetsInterface iphotosets = flickr.getPhotosetsInterface();
                            Photoset set = iphotosets.getInfo(request.getParameter("album"));

                            // TODO Creation de l'album 
                            com.unice.miage.oobdoo.entity.Album newAlbum = albumManager.creerAlbum(u, set.getTitle(), set.getDescription(), s);
                            utilisateurManager.addAlbum(u, newAlbum);

                            // TODO2 Recupération des photos pour les ajouter
                            for (Object o : iphotosets.getPhotos(set.getId(), 1000, 1)) {
                                Photo p = (Photo) o;
                                BufferedImage image = null;
                                try {
                                    URL url = new URL(p.getLargeUrl());
                                    uploadPhotoByUrl(u, newAlbum, url, p.getId());
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            forwardTo = "/AlbumServlet?action=list";
                            RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                            dp.forward(request, response);
                        } catch (Exception ex) {
                            Logger.getLogger(ImportServlet.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else {
                        System.out.println("No submit from form FLICKR import");
                        forwardTo = "import/index.jsp";
                    }
                    // Sinon on tombe dans le choix de l'album
                } else {
                    // On recupere l'access token flickr de l'utilisateur
                    String access_token_flickr = u.getAccess_token_flickr();

                    // Si il en a un
                    if (access_token_flickr != null) {
                        HashMap<String, String> lstAlbums = getListOfFLICKRAlbums(access_token_flickr);

                        request.setAttribute("lstAlbums", lstAlbums);
                        forwardTo = "import/flickr.jsp";
                        RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                        dp.forward(request, response);
                    }
                }
            }



        } else {
            RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
            dp.forward(request, response);
        }
    }

    private HashMap<String, String> getListOfFBAlbums(String access_token) {
        FacebookClient facebookClient = new DefaultFacebookClient(access_token);
        Connection<Album> lstAlbumFB = facebookClient.fetchConnection("me/albums", Album.class);

        HashMap<String, String> lstAlbums = new HashMap<String, String>();

        for (com.restfb.types.Album a : lstAlbumFB.getData()) {
            lstAlbums.put(a.getId(), a.getName());
        }
        return lstAlbums;
    }

    private HashMap<String, String> getListOfPICASAAlbums(String sessionToken) {
        try {
            PicasawebService ps = new PicasawebService("oobdoo");
            ps.setAuthSubToken(sessionToken, null);

            URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/default");

            Query myQuery = new Query(feedUrl);

            UserFeed myUserFeed = ps.getFeed(feedUrl, UserFeed.class);

            HashMap<String, String> lstAlbums = new HashMap<String, String>();

            for (AlbumEntry a : myUserFeed.getAlbumEntries()) {
                lstAlbums.put(a.getGphotoId(), a.getTitle().getPlainText());
            }
            return lstAlbums;

        } catch (Exception ex) {
            Logger.getLogger(ImportServlet.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    private HashMap<String, String> getListOfFLICKRAlbums(String token) {
        Auth auth;
        RequestContext requestContext;	// Used for making signed calls to Flickr

        try {
            Flickr flickr = new Flickr(FLICKR_API_KEY, FLICKR_API_SECRET, new REST());

            requestContext = RequestContext.getRequestContext();
            requestContext.setSharedSecret(FLICKR_API_SECRET);

            AuthInterface authInterface = flickr.getAuthInterface();
            auth = authInterface.checkToken(token);

            requestContext.setAuth(auth);

            HashMap<String, String> lstAlbums = new HashMap<String, String>();

            PhotosetsInterface iphotosets = flickr.getPhotosetsInterface();
            Iterator sets = iphotosets.getList(auth.getUser().getId()).getPhotosets().iterator();

            while (sets.hasNext()) {
                Photoset set = (Photoset) sets.next();
                lstAlbums.put(set.getId(), set.getTitle());
            }

            return lstAlbums;

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    private void uploadPhotoByUrl(Utilisateur u, com.unice.miage.oobdoo.entity.Album newAlbum, URL url, String idPhoto) throws IOException {
        BufferedImage image = null;
        image = ImageIO.read(url);

        String path = this.getServletContext().getInitParameter("PATH");

        System.out.println(path + "/upload/" + u.getId() + "/" + newAlbum.getId() + "/" + idPhoto + ".jpg");

        ImageIO.write(image, "jpg", new File(path + "upload/" + u.getId() + "/" + newAlbum.getId() + "/" + idPhoto + ".jpg"));

        // THUMB 140* - PAGE D'UN ALBUM
        Image image140 = new Image(path + "upload/" + u.getId() + "/" + newAlbum.getId() + "/" + idPhoto + ".jpg");
        image140.setWidth(140); //set width, adjusts height to maintain aspect ratio

        image140.saveAs(path + "upload/" + u.getId() + "/" + newAlbum.getId() + "/" + idPhoto + "_thumb_140.jpg");

        // THUMB 500* - PAGE D'UNE PHOTO
        Image image500 = new Image(path + "upload/" + u.getId() + "/" + newAlbum.getId() + "/" + idPhoto + ".jpg");
        image500.setWidth(500); //set width, adjusts height to maintain aspect ratio

        image500.saveAs(path + "upload/" + u.getId() + "/" + newAlbum.getId() + "/" + idPhoto + "_thumb_500.jpg");

        // THUMB 224*220 PAGE ACCUEIL
        Image image224_220 = new Image(path + "upload/" + u.getId() + "/" + newAlbum.getId() + "/" + idPhoto + ".jpg");
        image224_220.setWidth(225);
        if (image224_220.getHeight() < 220) {
            image224_220.setHeight(221);
        }

        int x = (image224_220.getWidth() / 2) - (224 / 2);
        int y = (image224_220.getHeight() / 2) - (220 / 2);

        image224_220.crop(x, y, 224, 220);
        image224_220.saveAs(path + "upload/" + u.getId() + "/" + newAlbum.getId() + "/" + idPhoto + "_thumb_224.jpg");

        com.unice.miage.oobdoo.entity.Photo newP = photoManager.creerPhoto(newAlbum, idPhoto, null, idPhoto + ".jpg", idPhoto + "_thumb_224.jpg", idPhoto + "_thumb_140.jpg", idPhoto + "_thumb_500.jpg");
        albumManager.addPhoto(newAlbum, newP);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
